﻿using System;
using System.Text;
using System.Net;
using System.Web;
using System.Threading;

namespace Scrobbler
{
    internal class CScrobblerSubmitter:IScrobblerSubmitter,IHistory
    {
        internal CScrobblerSubmitter(IScrobblerInfo ScrobblerInfo)
        {
            m_ScrobblerInfo = ScrobblerInfo;
            CHistory history = new CHistory(this);
            m_History = history;
        }

        private IScrobblerInfo m_ScrobblerInfo;
        private string m_LastPlayingNotificationStatus;
        private string m_LastSubmissionStatus;
        private CHistory m_History;

        #region IScrobblerSubmitter Members

        public string LastPlayingNotificationStatus
        {
            get { return m_LastPlayingNotificationStatus; }
        }

        public string LastSubmissionStatus
        {
            get { return m_LastSubmissionStatus; }
        }

      
        public bool SubmitPlayingNotification(string artist,string track,string album,
                                                            string seconds,string TrackNumber,string TrackId)
        {          
            bool retval;           
            string values = "?s=" +
                HttpUtility.UrlEncode(m_ScrobblerInfo.SessionID,Encoding.UTF8) + 
                "&a=" + HttpUtility.UrlEncode(artist, Encoding.UTF8)
                + "&t=" + HttpUtility.UrlEncode(track, Encoding.UTF8) 
                + "&b=" + HttpUtility.UrlEncode(album,Encoding.UTF8)
                + "&l=" + HttpUtility.UrlEncode(seconds,Encoding.UTF8) +
                "&n=" + HttpUtility.UrlEncode(TrackNumber, Encoding.UTF8) + "&m=" + 
                HttpUtility.UrlEncode(TrackId,Encoding.UTF8);

            string url = m_ScrobblerInfo.NowPlayingURL + values;

            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            HttpWebResponse WebResponse = (HttpWebResponse)request.GetResponse();

            switch (WebResponse.StatusDescription)
            {
                case "OK":
                    retval = true;
                    m_LastPlayingNotificationStatus = WebResponse.StatusDescription;
                    break;
                case "BADSESSION":
                    retval = false;
                    m_LastPlayingNotificationStatus = WebResponse.StatusDescription;
                    break;
                default:
                    retval = false;
                    m_LastPlayingNotificationStatus = WebResponse.StatusDescription;
                    break;
            }

            WebResponse.Close();

            return retval;
        }

       
        public bool SubmitTrack(string artist,string track,string lenght,
                                    string album,string TrackNumber,string TrackID)
        {
            bool retval;
            string source = "P";
            string rating = " ";

            string values = 
                "?s=" + HttpUtility.UrlEncode(m_ScrobblerInfo.SessionID,Encoding.UTF8) + 
                "&a[0]=" + HttpUtility.UrlEncode(artist, Encoding.UTF8) + 
                "&t[0]=" + HttpUtility.UrlEncode(track,Encoding.UTF8)+ 
                "&i[0]=" + HttpUtility.UrlEncode(CTime.GetUnixTime(),Encoding.UTF8) + 
                "&o[0]=" + HttpUtility.UrlEncode(source,Encoding.UTF8) + 
                "&r[0]=" + HttpUtility.UrlEncode(rating,Encoding.UTF8) +
                "&l[0]=" + HttpUtility.UrlEncode(lenght,Encoding.UTF8) +
                "&b[0]=" + HttpUtility.UrlEncode(album, Encoding.UTF8) + 
                "&n[0]=" + HttpUtility.UrlEncode(TrackNumber,Encoding.UTF8) +
                "&m[0]=" + HttpUtility.UrlEncode(TrackID,Encoding.UTF8);

            string url = m_ScrobblerInfo.SubmissionURL + values;

            WebRequest request = WebRequest.Create(url);
            request.Method = "POST";
            HttpWebResponse WebResponse = (HttpWebResponse)request.GetResponse();

            switch (WebResponse.StatusDescription)
            {
                case "OK":
                    retval = true;
                    m_LastSubmissionStatus = WebResponse.StatusDescription;
                    break;
                case "BADSESSION":
                    retval = false;
                    m_LastSubmissionStatus = WebResponse.StatusDescription;
                    break;
                default: //Most likely to be FAILED<reason>
                    retval = false;
                    m_LastSubmissionStatus = WebResponse.StatusDescription;
                    break;
            }

            WebResponse.Close();

            if(m_LastSubmissionStatus !="OK")
                m_History.SubmitToCache(artist,track,lenght);

            return retval;
        }

        #endregion


        private void ReSubmitCache()
        {

            if (m_History.IsCacheLocked)
                return;

            //0 artist
            //1 track
            //2 length
            string[] SongInfo = new string[m_History.CachedSongCount];
            int i;
            int counter = 0;

            for (i = 0; i < m_History.CachedSongCount; i++)
            {
                SongInfo = m_History.Cache[i].Split(';');
            
                if (SongInfo.Length < 1) break;

                if (this.SubmitTrack(SongInfo[0],
                                        SongInfo[1],
                                        SongInfo[2], "", "", "") == true)
                {
                    m_History.RemoveSongFromCache(i);
                }

                counter++;
            }
        }


        #region IHistory Members

        public void History_Timer_Tick(object info)
        {
            m_History.UpdateCache();
            this.ReSubmitCache();          
        }

        #endregion
    }
}
